package org.jeecg.modules.miniAppCustomerEndPoint.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.modules.miniAppCustomerEndPoint.entity.JxUserCouponDo;
import org.jeecg.modules.miniAppCustomerEndPoint.mapper.JxUserCouponMapper;
import org.jeecg.modules.platformMasterEndPoint.entity.JxCouponDo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class JxUserCouponServiceImpl {

    @Autowired
    private JxUserCouponMapper jxUserCouponMapper;

    /**
     * 查询用户领取优惠券后的表 jx_user_coupon
     * @param siteId
     * @param storeId
     * @param userId
     * @return
     */
    public List<JSONObject> checkAvailiableCouponsByStoreId(String siteId, String storeId, String userId) {

        List<JSONObject> formatedCoupons = new ArrayList<>();
        // select * from jx_coupons where coupon_name != '新手大礼包' and (store_ids = '*' or store_ids like concat(concat('%',#{storeId}),'%'))
        List<JxCouponDo> coupons = jxUserCouponMapper.queryAvaliableCouponsByStoreId(siteId, storeId, LocalDateTime.now());
        if (coupons != null && coupons.size() >0) {
            for (int i = 0 ; i < coupons.size(); i ++) {
                JxCouponDo jxCouponDo = coupons.get(i);
                JSONObject formatedCoupon = new JSONObject();
                formatedCoupon.put("couponId", jxCouponDo.getId());
                formatedCoupon.put("couponName", jxCouponDo.getCouponName());
                formatedCoupon.put("couponValue", jxCouponDo.getCouponValue());
                formatedCoupon.put("amountPerUser", jxCouponDo.getAmountPerUser());
                if (userId == null) {
                    // 用户id为null，表示接口调用时未携带token，此时表示用户没有授权登录，此时优惠券领取状态为 未领取
                    formatedCoupon.put("received", false);
                } else {
                    // 查询 用户是否已经领取了该站点，该店铺的优惠券
                    List<JxUserCouponDo> alreadyReceivedThisCoupon = jxUserCouponMapper.selectList(new LambdaQueryWrapper<JxUserCouponDo>()
                            .eq(JxUserCouponDo::getSiteId, siteId).eq(JxUserCouponDo::getStoreId, storeId)
                            .eq(JxUserCouponDo::getUserId, userId).eq(JxUserCouponDo::getCouponId, jxCouponDo.getId()));

                    if (alreadyReceivedThisCoupon != null && alreadyReceivedThisCoupon.size() > 0) {
                        formatedCoupon.put("received", true);
                    } else {
                        formatedCoupon.put("received", false);
                    }
                }

                formatedCoupons.add(formatedCoupon);
            }
        }
        return formatedCoupons;
    }
}
